package com.itchen.school.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public final class SpringContextUtils implements ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(SpringContextUtils.class);
    private static ApplicationContext APPLICATION_CONTEXT;

    public SpringContextUtils() {}

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.debug("ApplicationContext registed-->{}", applicationContext);
        APPLICATION_CONTEXT = applicationContext;
        BeanUtils.beanSupplier = SpringContextUtils::getBean;
        BeanUtils.beanSupplierByString = SpringContextUtils::getBeanByName;
        BeanUtils.resourceLoaderFunc = SpringContextUtils::getResources;
    }

    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }

    public static <T> T getBean(Class<T> type) {
        return APPLICATION_CONTEXT.getBean(type);
    }

    public static <T> T getBeanByName(String beanName) {
        return (T) APPLICATION_CONTEXT.getBean(beanName);
    }

    public static Resource[] getResources(String pattern) {
        try {
            return APPLICATION_CONTEXT.getResources(pattern);
        } catch (IOException var2) {
            var2.printStackTrace();
            return null;
        }
    }

}
